package com.hnjd.headline.controller;


import com.hnjd.headline.pojo.Headline;
import com.hnjd.headline.pojo.dto.HeadlineEditEcho;
import com.hnjd.headline.service.HeadlineService;
import com.hnjd.headline.utils.Result;
import com.hnjd.headline.utils.ResultCodeEnum;
import com.hnjd.headline.utils.TokenHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/headline")
@CrossOrigin
public class HeadlineController {

    @Autowired
    private TokenHelper tokenHelper;

    @Autowired
    private HeadlineService headlineService;

    /**
     * 发布新闻
     * @param headline 新闻内容
     * @param token 用户token
     * @return 发布结果
     */
    @PostMapping("/publish")
    public Result publish(@RequestBody Headline headline, @RequestHeader String token){
        // 获取用户id
        int userId = tokenHelper.getUserId(token).intValue();
        // 设置新闻相关信息
        headline.setPublisher(userId);  // 作者id
        Date now = new Date();
        headline.setCreateTime(now);    // 创建时间
        headline.setUpdateTime(now);    // 更新时间
        headline.setPageViews(0);      // 阅读量

        // 保存
        headlineService.save(headline);

        return Result.ok();
    }

    @PostMapping("/findHeadlineByHid")
    public Result findHeadlineByHid(@RequestParam Integer hid){
        if(hid == null) {
            return Result.build(ResultCodeEnum.BAD_REQUEST);
        }

        HeadlineEditEcho echo = headlineService.findHeadlineEditEchoByHid(hid);

        if(echo == null) {
            throw new RuntimeException("未找到新闻");
        }

        Map<String, Object> data = Map.of("headline", echo);

        return Result.ok(data);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Headline headline){
        if(headline == null) {
            return Result.build(ResultCodeEnum.BAD_REQUEST);
        }

        try {
            // 设置更新时间
            headline.setUpdateTime(new Date());
            // 更新
            headlineService.updateById(headline);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.ok();
    }

    @PostMapping("/removeByHid")
    public Result removeByHid(@RequestParam Integer hid){
        if (hid == null) {
            return Result.build(ResultCodeEnum.BAD_REQUEST);
        }

        try {
           headlineService.removeById(hid);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return Result.ok();
    }
}
